<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>房屋管理</title>
    <script src="../js/axios-0.18.0.js"></script>
    <script src="../js/axios-interceptors.js"></script>
    <script src="../js/vue3.js"></script>
    <script src="../js/element-plus.js"></script>
    <script src="../js/icons-vue.js"></script>
    <script src="../js/zh-cn.js"></script>
    <link href="../css/index.css" rel="stylesheet"/>
    <style>
        body {
            margin: 0;
            padding: 20px;
            font-family: "Helvetica Neue", Arial, sans-serif;
            background: #f4f6f9;
        }

        .search-container {
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
            margin-bottom: 20px;
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            align-items: center;
        }

        .search-container .el-form-item {
            margin: 0;
        }

        .table-container {
            background: #fff;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
        }

        .pagination-container {
            margin-top: 15px;
            display: flex;
            justify-content: flex-end;
        }
    </style>
</head>
<body>
<div id="app">
    <!-- 搜索区域 -->
    <div>
        <el-form :inline="true" class="search-container">
            <el-form-item label="房屋编号">
                <el-input v-model="searchForm.houseNo" placeholder="请输入房屋编号" clearable></el-input>
            </el-form-item>

            <el-form-item label="入住时间">
                <el-date-picker
                        v-model="dateRange"
                        type="daterange"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"></el-date-picker>
            </el-form-item>

            <!-- 新增：空的 form-item，强制换行 -->
            <el-form-item style="width: 100%;"></el-form-item>

            <el-form-item label="房屋状态" >
                <el-select v-model="searchForm.state" placeholder="请选择状态"  clearable style="width: 150px;">
                    <el-option v-for="state in states"  :key="state.stateId"
                               :label="state.stateName" :value="state.stateId"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="业主" width="100">
                <el-select v-model="searchForm.ownerId" placeholder="请选择业主" clearable style="width: 150px;">
                    <el-option v-for="owner in owners" :key="owner.id"
                               :label="owner.name" :value="owner.id"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="handleSearch">搜索</el-button>
                <el-button @click="handleReset">重置</el-button>
                <el-button type="success" @click="handleAdd">新增房屋</el-button>
                <el-button type="warning" @click="handleExport">导出Excel</el-button>
            </el-form-item>
        </el-form>
    </div>


    <!-- 表格 -->
    <div class="table-container">
        <el-table :data="tableData"
                  border stripe style="width: 100%">
            <el-table-column prop="id" label="编号" width="80"></el-table-column>
            <el-table-column prop="houseNo" label="房号" width="100"></el-table-column>
            <el-table-column prop="floor" label="楼层" width="80"></el-table-column>
            <el-table-column prop="area" label="面积(㎡)" width="100"></el-table-column>
            <el-table-column prop="liveTime" label="入住时间" :formatter="formatTime" width="150"></el-table-column>
            <el-table-column prop="state" label="房间状态" width="100">
                <template #default="scope">
                    <el-tag v-if="scope.row.state===1" class="ml-2" type="primary">已入住</el-tag>
                    <el-tag v-if="scope.row.state===0" class="ml-2" type="error">未入住</el-tag>
                    <el-tag v-if="scope.row.state===2" class="ml-2" type="success">已出租</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="building.buildingName" label="楼名" width="120"></el-table-column>
            <el-table-column prop="building.location" label="单元" width="80"></el-table-column>
            <el-table-column prop="owner.name" label="姓名" width="100">
                <template #default="scope">
                    <el-tag v-if="scope.row.owner===null" class="ml-2" type="success">空置</el-tag>
                    <el-tag v-else class="ml-2" type="error">{{scope.row.owner.name}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="owner.telephone" label="电话" width="150">
                <template #default="scope">
                    <el-tag v-if="scope.row.owner===null" class="ml-2" type="error">无</el-tag>
                    <el-tag v-else class="ml-2" type="success">{{scope.row.owner.telephone}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="remarks" label="备注"></el-table-column>
            <el-table-column label="操作" width="180">
                <template #default="scope">
                    <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination
                    :background="true"
                    :total="total"
                    :page-sizes="[5, 10, 15]"
                    layout="total, sizes, prev, pager, next, jumper"
                    v-model:page-size="pageSize"
                    v-model:current-page="pageNum"
                    @size-change="handleSizeChange"
                    @current-change="handlePageChange"></el-pagination>
        </div>
    </div>

    <!-- 新增/修改房屋弹窗 -->
    <div>
        <el-dialog title="新增/修改房屋"
                   v-model="dialogVisible"
                   :before-close="closeDialog"
                   width="500px">
            <el-form :model="houseForm" ref="houseFormRef" :rules="rules" label-width="100px">
                <!-- 房号（必填） -->
                <el-form-item label="房号" prop="houseNo" >
                    <el-input v-model="houseForm.houseNo" placeholder="请输入房号"></el-input>
                </el-form-item>

                <!-- 楼层（必填） -->
                <el-form-item label="楼层" prop="floor" >
                    <el-input v-model.number="houseForm.floor" placeholder="请输入楼层"></el-input>
                </el-form-item>

                <!-- 面积 -->
                <el-form-item label="面积（㎡）">
                    <el-input v-model.number="houseForm.area" placeholder="请输入面积（㎡）"></el-input>
                </el-form-item>

                <!-- 入住时间（必填） -->
                <el-form-item label="入住时间" prop="liveTime" >
                    <el-date-picker v-model="houseForm.liveTime" type="date" placeholder="选择日期"></el-date-picker>
                </el-form-item>

                <!-- 房间状态（必填，下拉框） -->
                <el-form-item label="房间状态" prop="state">
                    <el-select v-model="houseForm.state" placeholder="请选择房间状态">
                        <el-option v-for="state in states"  :key="state.stateId"
                                   :label="state.stateName" :value="state.stateId"></el-option>
                    </el-select>
                </el-form-item>

                <!-- 所属楼（下拉框） -->
                <el-form-item label="所属楼">
                    <el-select v-model="houseForm.buildingId" placeholder="请选择所属楼">
                        <el-option
                                v-for="building in buildingList"
                                :key="building.buildingId"
                                :label="building.buildingName"
                                :value="building.buildingId">
                        </el-option>
                    </el-select>
                </el-form-item>

                <!-- 备注 -->
                <el-form-item label="备注">
                    <el-input v-model="houseForm.remarks" type="textarea" placeholder="备注信息"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="closeDialog">取消</el-button>
                <el-button type="primary" @click="handleSave">保存</el-button>
            </template>
        </el-dialog>
    </div>

</div>

<script>
    const {createApp, ref, reactive, onMounted, onUpdated} = Vue;
    const {ElMessage, ElMessageBox} = ElementPlus;
    const app = createApp({

        setup() {
            //弹窗显示状态
            const dialogVisible = ref(false);

            //表格数据
            const tableData = ref([]);

            //分页相关
            const total = ref(0);
            const pageSize = ref(10);
            const pageNum = ref(1);

            //搜索模型
            const dateRange=ref([])
            const searchForm = ref({
                houseNo: '',
                state: '',
                ownerId: '',
                end:'',
                start:''
            });
            // 搜索框重置功能
            const handleReset = () => {
                searchForm.value = {
                    houseNo: '',
                    state: '',
                    ownerId: '',
                    end: '',
                    start: ''
                };
                dateRange.value = [];
            };
            //搜索框房东的下拉框数据源
            const owners= ref([]);
            //搜索框房东的下拉框
            const initOwnerSelect = () => {
                axios.get(`/owner/getOwnerNameAndId`).then(
                    resp=>{
                        owners.value=resp.data.obj;
                    }
                )
            }
            //搜索框和弹窗所属楼状态的下拉框数据源
            const states= ref([]);
            //搜索框房屋状态的下拉框
            const initHouseState = () => {
                axios.get(`/house/getHouseStateNameAndId`).then(
                    resp=>{
                        states.value=resp.data.obj;
                    }
                )
            }

            //搜索摁钮
            const handleSearch=()=>{
                searchForm.value.start=dateRange.value[0];
                searchForm.value.end=dateRange.value[1];
                getHouseList();
            }

            //搜索框房屋状态的下拉框数据源
            const buildingList= ref([]);
            //搜索框房屋状态的下拉框
            const initBuildingList = () => {
                axios.get(`/building/selectBuildingIdAndName`).then(
                    resp=>{
                        buildingList.value=resp.data.obj;
                    }
                )
            }

            //弹窗数据源
            const houseForm=ref({})
            //新增房屋
            const handleAdd = () => {
                console.log("新增房屋");
                houseForm.value={
                    id:'',
                    houseNo:'',
                    floor:'',
                    area:'',
                    liveTime:'',
                    status:'',
                    buildingId:'',
                    remarks:''
                };
                dialogVisible.value = true;
            };

            //编辑房屋
            const handleEdit = (row) => {
                houseForm.value={
                    id: row.id,
                    houseNo:row.houseNo,
                    floor:row.floor,
                    area:row.area,
                    liveTime:row.liveTime,
                    state: row.state,
                    buildingId:row.buildingId,
                    remarks:row.remarks
                }
                console.log("row.buildingId的值：", row.buildingId);
                console.log("row.buildingId的类型：", typeof row.buildingId); // 输出 "number" 或 "string"
                dialogVisible.value = true;
            };

            //弹窗确定提交方法
            const handleSave = () => {
                houseFormRef.value.validate((valid) => {
                    if (valid) {
                        if (!houseForm.value.id) {
                            // 新增房屋
                            axios.post(`/house/addHouse`, houseForm.value).then(resp => {
                                if (resp.data.code === 200) {
                                    ElMessage.success(resp.data.msg);
                                    dialogVisible.value = false;
                                    getHouseList();
                                }
                            }).catch(error => {
                                ElMessage.error(error.response.data.msg);
                            });
                        } else {
                            // 编辑房屋
                            axios.put(`/house/updateHouse`, houseForm.value).then(resp => {
                                if (resp.data.code === 200) {
                                    ElMessage.success(resp.data.msg);
                                    // 编辑成功后，关闭弹窗并重新获取房屋列表
                                    dialogVisible.value = false;
                                    getHouseList();
                                }
                            }).catch(error => {
                                ElMessage.error(error.response.data.msg);
                            });
                        }
                    }
                });
            };

            //导出Excel
            const handleExport = () => {
                window.location.href="/house/download";
            };

            //弹窗表单引用
            const houseFormRef= ref(null);
            // 清空校验红字信息
            const clearValid = () => {
                if (houseFormRef && houseFormRef.value) {
                    houseFormRef.value.resetFields();
                }
            }
            //编辑弹窗的取消方法
            const closeDialog = () => {
                clearValid();
                dialogVisible.value = false;
            }


            //删除摁钮
            const handleDelete = (row) => {
                ElMessageBox.confirm('将永久删除该电影信息. 确定?', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                })
                    .then(() => {
                        axios.get(`/owner/getOwnerById/${row.id}`).then(resp=>{
                            if(resp.data.code===200){
                                ElMessage.error("该房屋已拥有业主，无法删除");
                            }else{
                                axios.delete(`/house/deleteHouse/${row.id}`).then(resp=>{
                                    if(resp.data.code===200){
                                        ElMessage.success(resp.data.msg);
                                    }
                                }).catch(error=>{
                                    ElMessage.error(error.response.data.msg)
                                })
                            }
                        })
                    })
            };

            //分页
            const handleSizeChange = (val) => {
                pageSize.value = val
                getHouseList()
            };
            const handlePageChange = (val) => {
                pageNum.value = val
                getHouseList()
            };



            // 获取房屋列表
            const getHouseList = () => {
                console.log('加载房屋数据')
                axios.post(`/house/${pageNum.value}/${pageSize.value}`,searchForm.value)
                    .then(resp=>{
                        tableData.value=resp.data.obj.data
                        total.value=resp.data.obj.total
                    })
                    .catch((error)=>{
                        ElMessage.error(error.response.data.msg)
                    })
            };

            // 格式化日期格式
            const formatTime = (row, column, cellValue, index) => {
                let d = new Date(cellValue);
                return d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
            };

            // 表单验证规则
            const rules = ref({
                houseNo: [
                    { required: true, message: '请输入房号', trigger: 'blur' }
                ],
                floor: [
                    { required: true, message: '请输入楼层', trigger: 'blur' }
                ],
                liveTime: [
                    { required: true, message: '请选择入住时间', trigger: 'change' }
                ],
                state: [
                    { required: true, message: '请选择房间状态', trigger: 'change' }
                ]
            });

            onMounted(()=>{
                getHouseList();
                initOwnerSelect();
                initHouseState();
                initBuildingList();
            })

            return {
                dialogVisible,
                searchForm,
                tableData,
                total,
                pageSize,
                pageNum,
                houseForm,
                houseFormRef,
                owners,
                states,
                dateRange,
                buildingList,
                handleReset,
                handleAdd,
                handleExport,
                handleEdit,
                handleDelete,
                handleSizeChange,
                handlePageChange,
                getHouseList,
                formatTime,
                rules,
                handleSave,
                closeDialog,
                clearValid,
                initOwnerSelect,
                initHouseState,
                handleSearch,
                initBuildingList,
            };
        }
    });
    app.use(ElementPlus, {
        locale: ElementPlusLocaleZhCn
    });
    // 注册 Element Plus 图标
    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
        app.component(key, component);
    }
    app.mount("#app");
</script>
</body>
</html>